#include <57header.h>

int main(int argc,char*argv[])
{
    char *port = "8081";
    char *ip = "192.168.106.129";

    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi(port));
    sockaddr.sin_addr.s_addr = inet_addr(ip);

    connect(socket_fd, (struct sockaddr *)&sockaddr , sizeof(sockaddr) );

    int epoll_fd = epoll_create(1);

    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = STDIN_FILENO;
    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, STDIN_FILENO,&event );

    struct epoll_event event_socket;
    event_socket.events = EPOLLIN;
    event_socket.data.fd = socket_fd;
    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, socket_fd,&event_socket );

    int tag = -1;
    while(1){

        // 创建一个就绪的数组
        struct epoll_event list[5];
        int num = epoll_wait(epoll_fd, list, 5, -1);

        for(int i=0; i<num; i++){
            struct epoll_event event = list[i];
            if(event.data.fd == STDIN_FILENO){
                char buf[60] = {0};
                read(STDIN_FILENO, buf, sizeof(buf));
                
                send(socket_fd, buf, strlen(buf), 0);

            }else if(event.data.fd == socket_fd){
                char buf[60] = {0};
                int ret = recv(socket_fd, buf, sizeof(buf), 0);
                if(ret == 0){
                    printf("服务器断开链接 \n");
                    tag = 0;
                    break;
                }
                printf("other: %s \n", buf);
            }
        }


        if(tag != -1){
            break;
        }
    }

    close(socket_fd);
    return 0;
}

